﻿using DbSync;
using DBSync.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DBSync.wpfPage
{
    /// <summary>
    /// Interaction logic for LoginSettingsPage.xaml
    /// </summary>
    public partial class ViewUser : Page
    {
        syncdbEntities syncdb;
        public static ViewUser instance;
        public ViewUser()
        {
            InitializeComponent();
            syncdb = new syncdbEntities();

        }

        private void loadOrganizationList(string orgName)
        {
            try
            {
                if (orgName == "" || orgName == null)
                {
                    var query = from o in syncdb.tbl_organization
                                where o.STATUS == 0
                                orderby o.INSERTDATE descending
                                select new { ORGANIZATIONS = o.ORGANIZATION_NAME };
                    var results = query.ToList();
                    organizationGridview.ItemsSource = results;

                }
                else
                {
                    var query = from o in syncdb.tbl_organization
                                where o.ORGANIZATION_NAME.Contains(txtOrganizationSearch.Text)
                                where o.STATUS == 0
                                orderby o.INSERTDATE descending
                                select new { ORGANIZATIONS = o.ORGANIZATION_NAME };
                    var results = query.ToList();
                    organizationGridview.ItemsSource = results;
                }
                if (organizationGridview.HasItems)
                {
                    organizationGridview.SelectedItem = organizationGridview.Items[0];
                    organizationGridview.ScrollIntoView(organizationGridview.Items[0]);
                    
                }
            }
            catch (Exception ex)
            {
                MSGWindow msq = new MSGWindow("Error", ex.Message);
                msq.Show();
            }


        }
        public static ViewUser Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ViewUser();
                }
                instance.loadOrganizationList(null);
                return instance;
            }
        }

        private void txtUsername_TextChanged(object sender, TextChangedEventArgs e)
        {
            loadOrganizationList(txtOrganizationSearch.Text);
        }

        private void Page_Loaded_1(object sender, RoutedEventArgs e)
        {
            MainWindow.Instance.btn_view_organization.Visibility = System.Windows.Visibility.Hidden;
            MainWindow.Instance.btn_add_organization.Visibility = System.Windows.Visibility.Visible;
        }

        private void Page_Loaded_2(object sender, RoutedEventArgs e)
        {
            MainWindow.Instance.btn_add_organization.Visibility = System.Windows.Visibility.Visible;
            MainWindow.Instance.btn_view_organization.Visibility = System.Windows.Visibility.Hidden;
        }

        private void organizationGridview_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (organizationGridview.SelectedValue != null)
            {
                string selection = organizationGridview.SelectedValue.ToString();
                string orgName = selection.Split('=')[1].Split(' ')[1];
                loadUserList(orgName);
            }
        }

        private void loadUserList(string orgName)
        {
            if (orgName == null)
            {
                string selection = organizationGridview.SelectedValue.ToString();
                orgName = selection.Split('=')[1].Split(' ')[1];
            }
            try
            {
                var query = from u in syncdb.tbl_user
                            join o in syncdb.tbl_organization on u.ORGANIZATION_ID equals o.ID
                            where o.ORGANIZATION_NAME.Contains(orgName)
                            where u.STATUS == 0
                            orderby u.INSERTDATE descending
                            select new { USERS = u.USERNAME };
                var results = query.ToList();
                userGridView.ItemsSource = results;
            }
            catch (Exception ex)
            {
                MSGWindow msq = new MSGWindow("Error", ex.Message);
                msq.Show();
            }
        }

        private void btn_delete_organization_Click(object sender, RoutedEventArgs e)
        {
            ConfirmationWindow cfw = new ConfirmationWindow("Delete Organization", "Are you sure to delete organization?");
            cfw.ShowDialog();
            if (ConfirmationWindow.isConfirm.Equals(MessageBoxResult.Yes))
            {

                string selection = organizationGridview.SelectedValue.ToString();
                string orgName = selection.Split('=')[1].Split(' ')[1];

                tbl_organization organization = (tbl_organization)syncdb.tbl_organization.Where(o => o.ORGANIZATION_NAME == orgName).First();

                bool isRemoved = deleteDatabaseFromServer(organization.ID);
                if (!isRemoved)
                {
                    MSGWindow msgw = new MSGWindow("Error", "Database cannot be deleted. Please contact administrator");
                    msgw.ShowDialog();
                    return;
                }
                else
                {
                    syncdb.tbl_organization.Remove(organization);
                    syncdb.SaveChanges();

                    MSGWindow msq = new MSGWindow("Delete Organization Successful", "Organization record deleted successfully.");
                    msq.ShowDialog();

                    loadOrganizationList(null);
                }
                

               
            }
        }

        private bool deleteDatabaseFromServer(int orgId)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = config.AppSettings.Settings;
                string server = settings[SyncKeys.HOST].Value;
                string port = settings[SyncKeys.PORT].Value;
                string username = settings[SyncKeys.USERNAME].Value;
                string password = settings[SyncKeys.PASSWORD].Value;

                SqlConnection conn = new SqlConnection("Server=" + server + "," + port + ";Integrated Security=False;User ID=" + username + ";Password=" + password + ";Application Name=30");
                String str = "USE master;  DROP DATABASE " + SyncKeys.PHRDBNAME_DEFAULT + "_" + orgId + "; ";
                SqlCommand command = new SqlCommand(str, conn);
                conn.Open();
                command.ExecuteNonQuery();

                str = "USE master;  DROP DATABASE " + SyncKeys.DCDRDBNAME_DEFAULT + "_" + orgId + "; ";
                command = new SqlCommand(str, conn);
                command.ExecuteNonQuery();

                conn.Close();

                return true;
            }
            catch (Exception ex)
            {
                MSGWindow msgw = new MSGWindow("Error", "Failed to delete database. Check Internet connection");
                //MSGWindow msgw = new MSGWindow("Error", ex.Message);
                msgw.ShowDialog();
                return false;
            }
        }

        private void btn_delete_user_Click(object sender, RoutedEventArgs e)
        {
            if (userGridView.SelectedIndex == -1)
            {
                MSGWindow msq = new MSGWindow("Delete User", "Please select user to delete.");
                msq.ShowDialog();
            }
            else
            {
                ConfirmationWindow cfw = new ConfirmationWindow("Delete User", "Are you sure to delete user?");
                cfw.ShowDialog();
                if (ConfirmationWindow.isConfirm.Equals(MessageBoxResult.Yes))
                {
                    string selection = userGridView.SelectedValue.ToString();
                    string userName = selection.Split('=')[1].Split(' ')[1];

                    tbl_user user = (tbl_user)syncdb.tbl_user.Where(u => u.USERNAME == userName).First();
                    syncdb.tbl_user.Remove(user);
                    syncdb.SaveChanges();

                    MSGWindow msq = new MSGWindow("Delete User Successful", "User record deleted successfully.");
                    msq.ShowDialog();

                    loadUserList(null);
                }
            }
        }





    }
}
